<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button class="btn">按钮一</button>
  <button class="btn">按钮二</button>
  <button class="btn">按钮三</button>
  <button class="btn">按钮四</button>
  <script>

    var btnEls = document.querySelectorAll(".btn")
    for (var i = 0; i < btnEls.length; i++) {
      var btn = btnEls[i];
      btn.onclick = function () {
        // 因为作用域的关系,函数被执行的时候 i已经编程了4 所以所有按钮都显示按钮4
        console.log(`按钮${i}发生了点击`)
      }
    }


    // 上述代码可以使用立即执行函数来解决问题
    for (var i = 0; i < btnEls.length; i++) {
      var btn = btnEls[i];
      (function (m) {
        btn.onclick = function () {
          console.log(`按钮${m}发生了点击`)
        }
      })(i)
    }
  </script>
</body>

</html>